import { useEffect, useState } from 'react'
import style from './index.module.less'
import { ErrorBlock, Skeleton } from 'antd-mobile'
import { getDataRequest } from './ajax'
import { awaitWrap, formatDate } from '@src/assets/js/tool'
import classNames from 'classnames'
import uuid from 'uuid'
import { useAppDispatch } from '@src/redux/hook'
import { push } from '@src/redux/reducers/pages'

async function initList (setLoading, setList) {
  setLoading(true)
  const [e, d] = await awaitWrap(getDataRequest())
  setLoading(false)
  if (e === null && d !== null) {
    setList(d.list instanceof Array ? d.list : [])
  }
}

function Item ({ data }) {
  const [active, setActive] = useState(false)
  const dispatch = useAppDispatch()
  return (
    <div className={classNames(style.item, {[style.active]: active})} onClick={() => {
      setActive(true)
      setTimeout(() => {
        setActive(false)
      }, 150)
    }}>
      <div className={style['item-inner']} onClick={() => {
        dispatch(push({ element: 'gonggaoDetail', title: '公告详情', id: uuid(), meta: { id: data.id } }))
      }}>
        <div className={style['item-title']}>{data.title}</div>
        <div className={style['item-date']}>{formatDate(data.release_datetime, 'YYYY-MM-DD')}</div>
      </div>
    </div>
  )
}

function Main () {
  const dispatch = useAppDispatch()
  const [loading, setLoading] = useState(true)
  const [list, setList] = useState([])
  useEffect(() => {
    initList(setLoading, setList)
  }, [])
  return (
    <div className={style.container}>
      <div className={style.header}>
        <span className={style.title}>公告列表</span>
        <a className={style.more} onClick={() => {
          dispatch(push({ element: 'gonggaoList', title: '公告列表', id: uuid() }))
        }}>全部</a>
      </div>
      <div className={style.list}>
        {
          !loading && list.length === 0 && (
            <ErrorBlock status='empty' title='暂无数据' description='' />
          )
        }
        {
          loading && (
            <div className={style.loading}>
              <Skeleton.Title animated />
              <Skeleton.Paragraph animated />
            </div>
          )
        }
        <div>
          {
            !loading && list.map((li, i) => {
              return <Item data={li} key={i} />
            })
          }
        </div>
      </div>
    </div>
  )
}

export default Main
